import os
import csv
import numpy as np
from base_logger import get_logger


# 在函数的参数中加上几个默认参数，在以后把这段代码模块化的时候很有帮助
def main(filenames_=None, filename_output='C.csv'):
    mats = {}
    # 如果有指定文件名就用那些文件名，没有指定就使用w默认
    filenames = ['A.csv', 'B.csv'] if filenames_ is None else filenames_
    for filename in filenames:
        if not os.path.exists(filename):
            logger.error('File %s not found!' % filename)
            return
        mats[filename] = []
        try:
            with open(filename, 'r') as f:
                reader = csv.reader(f)
                for row in reader:
                    try:
                        data = [float(x) for x in row]
                    except ValueError as e:
                        logger.error("Can't convert something to 'float'! %s" % str(e))
                        return
                    mats[filename].append(data)
        except IOError:
            logger.error('IOError when reading %s!' % filename)
            return
        # 转换成numpy的格式，方便进行矩阵运算
        mats[filename] = np.array(mats[filename])
        # 直接打印矩阵也会帮你优化对齐
        print(filename, ":\n", mats[filename])
    try:
        # numpy真的太方便了~
        c = np.matmul(mats[filenames[0]], mats[filenames[1]])
    except ValueError as e:
        logger.error('ValueError when trying to calc A * B: %s' % str(e))
        return
    print('A * B =')
    print(c)
    # numpy转回python的list格式
    c_list = c.tolist()
    print('c_list:', c_list)
    try:
        # 用newline=''是因为csv库写入的时候不知道为啥会多出空行...
        with open(filename_output, 'w', newline='') as f:
            writer = csv.writer(f)
            writer.writerows(c_list)
    except IOError:
        logger.error('IOError when writing %s!' % filename_output)
        return
    logger.info('Write to %s done.' % filename_output)


logger = get_logger(__name__)
if __name__ == '__main__':
    main()
